from flask_restful.reqparse import RequestParser
from flask_restful import Resource
from comment.modules import db
from flask import g,current_app
from datetime import datetime
from comment.modules.deal_record import DealRecord
from comment.utils.gen_trans_id import gen_trans_id
from financial.resource.transaction.const import DealType
from comment.modules.user import User
from comment.modules.invest_record import Invest_record
from comment.modules.account import Account
from comment.modules.expected_return import Expected_return
from financial.resource.transaction.serializers import ExpectedReturnPaginateSerializer


class InvestIncomeResource(Resource):
    """某个预期收益到期之后，获取当前的收益"""
    def post(self):
        rp = RequestParser()
        rp.add_argument('return_id')  # 指定预期收益的ID
        args = rp.parse_args()
        return_id = int(args.get('return_id'))

        uid = g.user_uid

        #  根据登陆的用户查询资金账户对象
        account = Account.query.filter(Account.userId == uid).first()
        #  查询当前指定的预期收益对象
        expected_income = Expected_return.query.filter(Expected_return.id == return_id).first()

        if expected_income:
            #  判断当前的预期收益是否可以 开始获取收益
            cur_date = datetime.now().date()
            expect_date = expected_income.expectedDate.date()
            if  cur_date > expect_date: #  如果当前日期大于 投资到期的日期
                try:
                    #  查询对应的投资记录对象
                    invest = Invest_record.query.filter(Invest_record.pId == expected_income.investRecord).first()
                    Invest_record.pStatus = 2   # 修改投资记录的状态

                    # 修改用户的资金账户
                    account.interestA += expected_income.expectedMoney # 修改已经赚取的利息
                    account.interestTotal -= expected_income.expectedMoney# 修改待收利息总额
                    account.investmentW -= invest.pAmount # 修改待收的本金总额
                    account.frozen -= invest.pAmou # 修改冻结资金总额
                    before_balance = account.balance
                    account.balance += (invest.pAmount + expected_income.expectedMoney) #修改账户余额
                    account.total -= expected_income.expectedMoney # 修改账户总金额

                    #新增一条交易记录
                    deal_num = gen_trans_id(DealType.income)
                    deal_log=DealRecord(aUserId=uid, aReceiveOrPay=1, aTransferSerialNo=deal_num,
                                          aTransferStatus=1, aBeforeTradingMoney=before_balance,
                                          aAmount=expected_income.expectedMoney, aAfterTradingMoney=account.balance,
                                          aDescreption='提取收益', aType=DealType.income.value)
                    db.session.add(deal_log)
                    db.session.commit()
                    return {'msg': 'success'}
                except Exception as e:
                    current_app.logger.error(e)
                    db.session.rollback()
                    return {'message':'系统出错啦'},500
            else:
                return {'message':'投资未到期','code':20001}
        else:

            return {'message': '没有找到对应的预期首页'},401

